import productApi from '@/api/project/ProductApi.js'
import productTypeApi from '@/api/base/ProductTypeApi'
import page from '@/mixins/page'
import productModelApi from "@/api/base/ProductModelApi";


export default {
    name: "product",
    mixins: [page],
    data() {
        return {
            files:[],
            // 参数
            params: {
                name: '',
                typeId: '',
                modelId: '',
                price: '',
                remark: '',
            },

            // 表单弹窗信息
            formDialog: {
                loading: false,
                title: '',
                state: '',
                visible: false,
            },
            // 表单数据
            formData: {
                name: '',
                typeId: '',
                modelId: '',
                price: '',
                remark: '',
                picPath:'',
            },
            detail: {
                visible: false,
                title: '详情',
                data: {},
            },
            rules: {
                name: [{required: true, message: "请输入产品名称", trigger: "blur"}],
                typeId: [{required: true, message: "请输入所属分类", trigger: "blur"}],
                modelId: [{required: true, message: "请输入所属型号", trigger: "blur"}],
                price: [{required: true, message: "请输入产品价格", trigger: "blur"}],
                remark: [{required: true, message: "请输入产品说明", trigger: "blur"}],
            },
            map: {
                productTypeTrees: [],
                productModelMap: new Map(),
                productModels: [],
            },
            view: {
                configurationFormVisible: false,
                configurationFormLoading: false,
                configurationFormState: "insert",
                configurationFormTitle: "新增配置",
            },
            configurationForm: {
                name:'',
                remark:''
            },
            configurationFormRules: {},
            dialogTableData:[],
            currentRow:{},
            allPremium:0
        }
    },
    watch: {
        'formData.typeId'(newValue, oldValue) {
            this.map.productModels = this.map.productModelMap.get(newValue)
            if (this.formData.modelId != null) {
                if (this.map.productModels === undefined) {
                    this.formData.modelId = null
                    return
                }
                var flag = false
                this.map.productModels.forEach(item => {
                    if (item.id === this.formData.modelId) {
                        flag = true
                    }
                })
                if (!flag) {
                    this.formData.modelId = null
                }
            }
        }
    },
    methods: {
        uploadSuccess(data){
            this.formData.picPath = data.path
            this.formData.fileId = data.id
        },
        init() {
            Promise.all([this.listProductTypeTree(),
                this.listProductModel()]).then(res => {
            })
        },
        /**
         * 加载产品分类树结构
         * @returns {Promise<void>}
         */
        listProductTypeTree() {
            return productTypeApi.listTree().then(res => {
                this.map.productTypeTrees = res.data[0].children
            })
        },
        listProductModel() {
            return this.$rq.list(productModelApi.url, {}).then(res => {
                this.map.productModels = res.data
                res.data.forEach(item => {
                    if (this.map.productModelMap.has(item.typeId)) {
                        this.map.productModelMap.get(item.typeId).push(item)
                    } else {
                        var items = [];
                        items.push(item)
                        this.map.productModelMap.set(item.typeId, items)
                    }
                })
            }).catch(err => {
                return
            })
        },
        // 查询
        page() {
            this.table.loading = true
            this.$rq.query(productApi.url, {
                ...this.params,
                ...this.sorting,
                pageSize: this.pagination.pageSize,
                pageOn: this.pagination.pageOn
            }).then(res => {
                if (res.data && Array.isArray(res.data.rows) && res.data.rows.length) {
                    this.pagination.total = res.data.total
                    this.table.data = res.data.rows
                } else {
                    this.total = 0
                    this.table.data = []
                }
            }).finally(() => {
                // 无论失败还是成功, 都执行的操作
                this.table.loading = false
            })
        },
        // 新增
        handleInsert() {
            this.formReset()
            this.formDialog.visible = true
            this.formDialog.title = '新增'
            this.formDialog.state = 'insert'
        },
        // 表单重置
        formReset() {
            if (this.$refs.form) {
                this.$refs.form.clearValidate()
                this.$refs.form.resetFields()
            }
        },
        // 设置表单
        formSet(data) {
            this.formData.id = data.id
            this.formData.name = data.name
            this.formData.typeId = data.typeId
            this.formData.modelId = data.modelId
            this.formData.price = data.price
            this.formData.remark = data.remark
        },
        /**
         * 设置某个产品的配置信息
         * @param row
         */
        setConfiguration({row}) {
            if (this.$refs.configurationForm) {
                this.$refs.configurationForm.clearValidate()
                this.$refs.configurationForm.resetFields()
            }
            this.view.configurationFormVisible = true
            this.view.configurationFormTitle = '新增'
            this.view.configurationFormState = 'insert'
            this.configurationForm.name = ''
            this.configurationForm.remark = ''
            this.allPremium = 0
            this.currentRow = row
            this.dialogTableData = []
        },
        // 编辑
        handleEdit({row}) {
            this.formReset()
            this.formSet(row)
            this.$nextTick(() => {
                this.formDialog.title = '修改'
                this.formDialog.state = 'edit'
                this.formDialog.visible = true
            })
        },
        // 删除(批量)
        handleDel() {
            if (this.table.selectionRows.length) {
                let ids = this.table.selectionRows.map(e => e.id)
                this.$confirm('确认删除?', {
                    title: '提示',
                    confirmButtonText: '删除',
                    type: 'warning',
                    beforeClose: (action, instance, done) => {
                        if (action == 'confirm') {
                            instance.confirmButtonLoading = true
                            instance.confirmButtonText = '执行中...'
                            this.$rq.deleteByIds(productApi.url, ids).then(res => {
                                this.$message.success('删除成功')
                                this.page()
                            }).finally(() => {
                                done()
                                instance.confirmButtonLoading = false;
                            })
                        } else {
                            done()
                        }
                    }
                })
            } else {
                this.$message.warning('请至少选择一行')
            }
        },
        /**
         * 保存配置设置
         */
        configurationFormSave() {
            if(this.view.configurationFormState == 'insert'){
                let params={
                    productId:this.currentRow.id,
                    name:this.configurationForm.name,
                    remark:this.configurationForm.remark,
                    total:this.allPremium,
                    details:this.dialogTableData
                }
                productApi.setConfiguration({...params}).then(res => {
                    this.$message.success('配置成功')
                    this.view.configurationFormVisible = false
                    this.page()
                })
            }else if(this.view.configurationFormState == 'edit'){
                let params={
                    id:this.configurationForm.id,
                    productId:this.configurationForm.productId,
                    name:this.configurationForm.name,
                    remark:this.configurationForm.remark,
                    total:this.allPremium,
                    details:this.dialogTableData
                }
                productApi.updateConfiguration({...params}).then(res => {
                    this.$message.success('修改成功')
                    this.view.configurationFormVisible = false
                    this.page()
                })
            }
        },
        formSave() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    if (this.formDialog.state === 'insert') {
                        this.formDialog.loading = true
                        this.$rq.insert(productApi.url, this.formData).then(res => {
                            this.formDialog.visible = false
                            this.page()
                        }).finally(() => {
                            this.formDialog.loading = false
                        })
                    } else if (this.formDialog.state === 'edit') {
                        this.formDialog.loading = true
                        this.$rq.updateById(productApi.url, this.formData).then(res => {
                            this.formDialog.visible = false
                            this.page()
                        }).finally(() => {
                            this.formDialog.loading = false
                        })
                    }
                }
            })
        },
        // 详情
        handleDetail({row, column, $index}) {
            this.detail.data = row
            this.detail.visible = true
        },
        // 关闭详情
        detailClose() {
            this.detail.visible = false
        },
        configurationFormClose() {
            this.view.configurationFormVisible = false
        },
        // 关闭表单
        formClose() {
            this.formDialog.visible = false
        },
        dialogInsert(){
            this.dialogTableData.push({
                configurationId:'',
                id:'',
                value:'',
                premium:'0.00',
                remark:''
            })
        },
        // 移除行
        removeLine(data, index) {
            this.dialogTableData.splice(index, 1)
            this.allPremium = 0
            this.dialogTableData.forEach(e => {
                this.allPremium += parseFloat(e.premium)
            })
        },
        editSubTableLine(data, index){
            this.view.configurationFormTitle = '修改'
            this.view.configurationFormState = 'edit'
            this.view.configurationFormVisible = true
            this.configurationForm.name = data.name
            this.configurationForm.productId = data.productId
            this.configurationForm.id = data.id
            this.configurationForm.remark = data.remark
            this.dialogTableData = data.details
            this.allPremium = 0
            data.details.forEach(e => {
                this.allPremium += e.premium
            })
        },
        premiumBlur(){
            this.allPremium = 0
            this.dialogTableData.forEach(e => {
                this.allPremium += parseFloat(e.premium)
            })
        }
    },
    mounted() {
        this.page()
    },
    created() {
        this.init()
    }
}
